Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Sets

Adding set items

Adding items in set : Different ways

A set is a built-in data type in Python that represents a mutable collection of unique elements. Here are some ways to add elements to a set:

1. Using the add() method:

This method adds a single element to the set.
Adding element in set using add() method in python # Create a set my_set = {1, 2, 3} print(f"Original Set: {my_set}") # Add an element to the set my_set.add(4) print(f"Set After Adding an Element: {my_set}")

Output

Original Set: {1, 2, 3} Set After Adding an Element: {1, 2, 3, 4}

2. Using the update() method:

This method can add multiple elements to the set. It can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are ignored.
Adding element in set using update() method in python # Create a set my_set = {1, 2, 3} print(f"Original Set: {my_set}") # Add multiple elements to the set my_set.update([4, 5, 6]) print(f"Set After Adding Multiple Elements: {my_set}")

Output

Original Set: {1, 2, 3} Set After Adding Multiple Elements: {1, 2, 3, 4, 5, 6}

3. Using the union() method:

This method returns a new set that contains all items from both sets. The original sets are not modified.
Adding element in set using union() method in python # Create two sets set1 = {1, 2, 3} set2 = {4, 5, 6} print(f"Original Sets: {set1}, {set2}") # Create a union of the two sets set3 = set1.union(set2) print(f"Union of Two Sets: {set3}")

Output

Original Sets: {1, 2, 3}, {4, 5, 6} Union of Two Sets: {1, 2, 3, 4, 5, 6}

4. Using the | operator:

This operator can also be used to get the union of two sets.
Adding element in set using | operator in python # Create two sets set1 = {1, 2, 3} set2 = {4, 5, 6} print(f"Original Sets: {set1}, {set2}") # Create a union of the two sets set3 = set1 | set2 print(f"Union of Two Sets: {set3}")

Output

Original Sets: {1, 2, 3}, {4, 5, 6} Union of Two Sets: {1, 2, 3, 4, 5, 6}

Remember, sets in Python are unordered collections of unique elements. When you add an element that is already in the set, Python will ignore it because sets cannot have duplicate elements. Also, sets are mutable, but they cannot contain mutable elements, such as lists or other sets. So you can add an integer or a string to a set, but you can’t add a list or a set.

  📌TAGS

★python ★ sets

Tutorials